# -*- coding: utf-8 -*-
'''
@Time : 2021/6/12 9:07
@description: 检查毕业生信息
@Author : yin
@Email : yylai24@163.com
@File : Check_BiYe.py
@Project : check-biye
'''

import pandas as pd
import os

import configparser
config = configparser.ConfigParser()
config.read("./config.ini",encoding='utf-8')

class Check:
    def __init__(self):
        self.allInformationPath = config["path"]["allInfoTablePath"]  # 总表路径
        self.infoTablesDir = config["path"]["infoTablesDir"]  # 分表根目录
        self.resultPath = config["path"]["resultPath"]
        self.year = config["path"]["year"]

    def deal_space(self, x):
        """
        去空函数
        :param x:字符串
        :return:去空字符串
        """
        return x.replace(" ", "")

    def get_one_year_all_data(self, path, year):
        """
        获取总数据
        :param path: 文件的路径
        :param year: 读取的年份
        :return:该年份的数据,表中是否含有班级信息
        """
        year = year + "年"
        year_data = pd.read_excel(path, sheet_name=year, dtype=object)
        flag = -1
        if set(['班级', '学号', '姓名']).issubset(year_data.columns):
            data = year_data.loc[:, ['姓名', '学号', '班级']].rename(
                columns={"姓名": "student_name", "学号": "student_id", "班级": "class"})
            data.dropna(axis=0, inplace=True)
            data['student_name']=data['student_name'].str.replace("·","·")
            data['student_name'] = data['student_name'].apply(self.deal_space)
            data['student_id'] = data['student_id'].apply(self.deal_space)
            data['class'] = data['class'].apply(self.deal_space)
            flag = 1  # 含有班级信息
        else:
            data = year_data.loc[:, ['姓名', '学号']].rename(columns={"姓名": "student_name", "学号": "student_id"})
            data.dropna(axis=0, inplace=True)
            data['student_name'] = data['student_name'].apply(self.deal_space)
            data['student_id'] = data['student_id'].apply(self.deal_space)
            flag = 0  # 表中没有班级信息
        data['flag'] = "总表数据"
        return data, flag

    def get_part_data(self, path):
        """
        获得识的数据
        :param path:分表路径
        :return:分表中的总数据
        """
        part_allInfo_data = pd.read_excel(path, dtype=object)
        part_allInfo_data = part_allInfo_data.loc[:, ['学号', '姓名']]
        part_allInfo_data.rename(columns={"学号": "student_id", "姓名": "student_name"}, inplace=True)

        # 去空
        part_allInfo_data.dropna(axis=0, inplace=True)

        # 检测哪一行是否含有学院,并将其删除
        if len(part_allInfo_data.loc[part_allInfo_data['student_id']=='学号',:])!=0:
            part_allInfo_data.drop(index=part_allInfo_data[part_allInfo_data['student_id'].isin(['学号'])].index.tolist(),
                                   inplace=True)
        # 将数据进行去空
        part_allInfo_data['student_id'] = part_allInfo_data['student_id'].apply(self.deal_space)
        part_allInfo_data['student_name'] = part_allInfo_data['student_name'].replace("•","·")
        part_allInfo_data['student_name'] = part_allInfo_data['student_name'].apply(self.deal_space)
        part_allInfo_data['flag'] = "分表数据"
        return part_allInfo_data

    def check_data(self, all_data, part_data):
        """
        见查数据表中的数据
        :param all_data:总表data
        :param part_data:分表data
        :return:不正确的数据
        """
        search_data = all_data.loc[all_data['student_id'].isin(list(part_data['student_id'])), :]
        data = pd.concat([part_data, search_data], axis=0, ignore_index=True)
        data['student_name'] = data['student_name'].apply(lambda x: x.replace("·", "").replace("•", ""))
        data.drop_duplicates(subset=['student_id', 'student_name'], keep=False, inplace=True)
        data.sort_values(by="student_id", inplace=True)
        return data

    def mkdir_path(self, path):
        """
        文件的创建
        :param path:输出路径
        :return:
        """
        if not os.path.exists(path):
            os.mkdir(path)

    def save_error_data(self, data, path):
        """
        保存错误数据
        :param data:错误数据
        :param path:保存路径
        :return:
        """
        self.mkdir_path(path)
        if not data.empty:
            data.rename(columns={"student_id": "学号", "student_name": "姓名"})
            data.to_excel(os.path.join(path,"{}_error.xlsx".format(self.year)), index=None)

    def get_all_excel(self, rootdir):
        """
        获取某文件夹底下所有Excel表格的路径
        :param rootdir: 文件夹路径
        :return: Excel表格路径列表
        """
        excel_path_list = []
        for root, dirs, files in os.walk(rootdir):
            for file in files:
                if file.endswith(".xlsx"):
                    file_path = os.path.join(root, file)
                    excel_path_list.append(file_path)
        return excel_path_list

    def run(self):
        all_data, flag = self.get_one_year_all_data(self.allInformationPath, self.year)
        excel_path_list = self.get_all_excel(self.infoTablesDir)
        for path in excel_path_list:
            part_data = self.get_part_data(path)
            error_data = self.check_data(all_data, part_data)
            self.save_error_data(error_data, self.resultPath)


